<?php
session_start();
include('../includes/config.php');
include('../includes/functions.php');

// 检查用户是否已登录，且是医生角色
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'doctor') {
    header("Location: ../login.php");
    exit();
}

// 获取医生信息
$doctor_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users u JOIN doctors d ON u.id = d.user_id WHERE u.id = ?");
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$doctor_info = $stmt->get_result()->fetch_assoc();
$stmt->close();

// 检查是否来自预约
$appointment_id = isset($_GET['appointment_id']) ? intval($_GET['appointment_id']) : 0;
$appointment = null;
$patient = null;

if ($appointment_id > 0) {
    // 获取预约信息
    $stmt = $conn->prepare("
        SELECT a.*, p.id as patient_id, p.name as patient_name, p.gender, p.birthday, p.phone, p.id_card, 
               p.address, p.medical_history, p.allergy
        FROM appointments a 
        JOIN patients p ON a.patient_id = p.id 
        WHERE a.id = ? AND a.doctor_id = ?
    ");
    $stmt->bind_param("ii", $appointment_id, $doctor_info['id']);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $appointment = $result->fetch_assoc();
        $patient = [
            'id' => $appointment['patient_id'],
            'name' => $appointment['patient_name'],
            'gender' => $appointment['gender'],
            'birthday' => $appointment['birthday'],
            'phone' => $appointment['phone'],
            'id_card' => $appointment['id_card'],
            'address' => $appointment['address'],
            'medical_history' => $appointment['medical_history'],
            'allergy' => $appointment['allergy']
        ];
    }
    $stmt->close();
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 获取表单数据
    $patient_id = isset($_POST['patient_id']) ? intval($_POST['patient_id']) : 0;
    $main_complaint = isset($_POST['main_complaint']) ? trim($_POST['main_complaint']) : '';
    $present_illness = isset($_POST['present_illness']) ? trim($_POST['present_illness']) : '';
    $diagnosis = isset($_POST['diagnosis']) ? trim($_POST['diagnosis']) : '';
    $treatment = isset($_POST['treatment']) ? trim($_POST['treatment']) : '';
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
    
    // 处方药品数据
    $medicine_ids = isset($_POST['medicine_id']) ? $_POST['medicine_id'] : [];
    $dosages = isset($_POST['dosage']) ? $_POST['dosage'] : [];
    $frequencies = isset($_POST['frequency']) ? $_POST['frequency'] : [];
    $days_array = isset($_POST['days']) ? $_POST['days'] : [];
    $quantities = isset($_POST['quantity']) ? $_POST['quantity'] : [];
    $medicine_notes = isset($_POST['medicine_notes']) ? $_POST['medicine_notes'] : [];
    
    $errors = [];
    
    // 验证表单数据
    if ($patient_id <= 0) {
        $errors[] = "请选择患者";
    }
    if (empty($main_complaint)) {
        $errors[] = "请填写主诉";
    }
    if (empty($diagnosis)) {
        $errors[] = "请填写诊断结果";
    }
    
    // 如果没有错误，则保存记录
    if (empty($errors)) {
        // 开始事务
        $conn->begin_transaction();
        
        try {
            // 插入病历记录
            $stmt = $conn->prepare("
                INSERT INTO medical_records 
                (patient_id, doctor_id, appointment_id, main_complaint, present_illness, diagnosis, treatment, notes) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            // 如果没有预约ID，设为null
            $app_id = $appointment_id > 0 ? $appointment_id : null;
            
            $stmt->bind_param("iiisssss", $patient_id, $doctor_info['id'], $app_id, $main_complaint, 
                            $present_illness, $diagnosis, $treatment, $notes);
            $stmt->execute();
            
            $record_id = $conn->insert_id;
            $stmt->close();
            
            // 处理处方药品
            if (!empty($medicine_ids)) {
                $stmt = $conn->prepare("
                    INSERT INTO prescription_medicines 
                    (medical_record_id, medicine_id, dosage, frequency, days, quantity, notes) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                
                foreach ($medicine_ids as $key => $medicine_id) {
                    if (!empty($medicine_id) && !empty($dosages[$key]) && !empty($frequencies[$key]) 
                        && !empty($days_array[$key]) && !empty($quantities[$key])) {
                        
                        $stmt->bind_param("iisssis", $record_id, $medicine_id, $dosages[$key], $frequencies[$key], 
                                        $days_array[$key], $quantities[$key], $medicine_notes[$key]);
                        $stmt->execute();
                    }
                }
                
                $stmt->close();
            }
            
            // 如果是从预约创建的，则更新预约状态为已完成
            if ($appointment_id > 0) {
                $stmt = $conn->prepare("UPDATE appointments SET status = 'completed' WHERE id = ?");
                $stmt->bind_param("i", $appointment_id);
                $stmt->execute();
                $stmt->close();
            }
            
            // 提交事务
            $conn->commit();
            
            // 设置成功消息并重定向
            $_SESSION['success_msg'] = "病历记录创建成功！";
            header("Location: record_details.php?id=" . $record_id);
            exit();
            
        } catch (Exception $e) {
            // 回滚事务
            $conn->rollback();
            $errors[] = "数据保存失败：" . $e->getMessage();
        }
    }
}

// 获取所有患者列表（用于下拉选择）
$stmt = $conn->prepare("SELECT id, name, id_card FROM patients ORDER BY name");
$stmt->execute();
$patients = $stmt->get_result();
$stmt->close();

// 获取所有药品列表
$stmt = $conn->prepare("SELECT id, name, specification, unit, price FROM medicines ORDER BY name");
$stmt->execute();
$medicines = $stmt->get_result();
$stmt->close();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新建病历 - 医生工作站</title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
    <link rel="stylesheet" href="/assets\css/all_de197510.min.css">
    <link rel="stylesheet" href="/assets\css/select2_00091487.min.css">
    <link rel="stylesheet" href="/assets\css/select2-bootstrap-5-theme_1d4ba57f.min.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-dark sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <img src="../assets/images/hospital-logo.png" alt="医院标志" class="img-fluid rounded-circle mx-auto d-block" style="width: 80px;">
                        <h5 class="text-white mt-2"><?php echo htmlspecialchars($doctor_info['name']); ?></h5>
                        <p class="text-muted"><?php echo htmlspecialchars($doctor_info['department_name']); ?></p>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white" href="index.php">
                                <i class="fas fa-home"></i> 工作台首页
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="appointments.php">
                                <i class="fas fa-calendar-check"></i> 预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="patients.php">
                                <i class="fas fa-user-injured"></i> 患者管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active text-white" href="records.php">
                                <i class="fas fa-notes-medical"></i> 病历管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="prescriptions.php">
                                <i class="fas fa-prescription"></i> 处方管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="schedule.php">
                                <i class="fas fa-clock"></i> 排班管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="profile.php">
                                <i class="fas fa-user-md"></i> 个人信息
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="../logout.php">
                                <i class="fas fa-sign-out-alt"></i> 退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">新建病历</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="records.php" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-arrow-left"></i> 返回列表
                        </a>
                    </div>
                </div>

                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger">
                        <ul class="mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <form method="post" action="" class="needs-validation" novalidate>
                    <!-- 患者信息 -->
                    <div class="card mb-4">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0">患者信息</h5>
                        </div>
                        <div class="card-body">
                            <?php if ($patient): ?>
                                <input type="hidden" name="patient_id" value="<?php echo $patient['id']; ?>">
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <p><strong>姓名：</strong> <?php echo htmlspecialchars($patient['name']); ?></p>
                                    </div>
                                    <div class="col-md-4">
                                        <p><strong>性别：</strong> <?php echo htmlspecialchars($patient['gender']); ?></p>
                                    </div>
                                    <div class="col-md-4">
                                        <?php
                                        $birthday = new DateTime($patient['birthday']);
                                        $today = new DateTime();
                                        $age = $birthday->diff($today)->y;
                                        ?>
                                        <p><strong>年龄：</strong> <?php echo $age; ?>岁</p>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <p><strong>身份证：</strong> <?php echo htmlspecialchars($patient['id_card']); ?></p>
                                    </div>
                                    <div class="col-md-4">
                                        <p><strong>电话：</strong> <?php echo htmlspecialchars($patient['phone']); ?></p>
                                    </div>
                                    <div class="col-md-4">
                                        <p><strong>地址：</strong> <?php echo htmlspecialchars($patient['address']); ?></p>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <p><strong>既往病史：</strong> <?php echo nl2br(htmlspecialchars($patient['medical_history'] ?: '无')); ?></p>
                                    </div>
                                    <div class="col-md-6">
                                        <p><strong>过敏史：</strong> <?php echo nl2br(htmlspecialchars($patient['allergy'] ?: '无')); ?></p>
                                    </div>
                                </div>
                            <?php else: ?>
                                <div class="row mb-3">
                                    <label for="patient_id" class="col-md-2 col-form-label">选择患者</label>
                                    <div class="col-md-10">
                                        <select class="form-select select2" id="patient_id" name="patient_id" required>
                                            <option value="">请选择患者</option>
                                            <?php while ($row = $patients->fetch_assoc()): ?>
                                                <option value="<?php echo $row['id']; ?>">
                                                    <?php echo htmlspecialchars($row['name'] . ' (' . $row['id_card'] . ')'); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                        <div class="invalid-feedback">请选择患者</div>
                                    </div>
                                </div>
                                <div id="patient_info" class="mt-3 d-none">
                                    <!-- 这里将通过AJAX加载患者详细信息 -->
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if ($appointment): ?>
                    <div class="card mb-4">
                        <div class="card-header bg-info text-white">
                            <h5 class="mb-0">预约信息</h5>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <p><strong>预约时间：</strong> <?php echo htmlspecialchars($appointment['appointment_date'] . ' ' . $appointment['appointment_time']); ?></p>
                                </div>
                                <div class="col-md-8">
                                    <p><strong>症状描述：</strong> <?php echo nl2br(htmlspecialchars($appointment['symptoms'] ?: '无')); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- 诊断信息 -->
                    <div class="card mb-4">
                        <div class="card-header bg-success text-white">
                            <h5 class="mb-0">诊断信息</h5>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label for="main_complaint" class="form-label">主诉</label>
                                <textarea class="form-control" id="main_complaint" name="main_complaint" rows="3" required><?php echo isset($_POST['main_complaint']) ? htmlspecialchars($_POST['main_complaint']) : ''; ?></textarea>
                                <div class="invalid-feedback">请填写患者主诉</div>
                            </div>
                            <div class="mb-3">
                                <label for="present_illness" class="form-label">现病史</label>
                                <textarea class="form-control" id="present_illness" name="present_illness" rows="3"><?php echo isset($_POST['present_illness']) ? htmlspecialchars($_POST['present_illness']) : ''; ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="diagnosis" class="form-label">诊断结果</label>
                                <textarea class="form-control" id="diagnosis" name="diagnosis" rows="3" required><?php echo isset($_POST['diagnosis']) ? htmlspecialchars($_POST['diagnosis']) : ''; ?></textarea>
                                <div class="invalid-feedback">请填写诊断结果</div>
                            </div>
                            <div class="mb-3">
                                <label for="treatment" class="form-label">治疗方案</label>
                                <textarea class="form-control" id="treatment" name="treatment" rows="3"><?php echo isset($_POST['treatment']) ? htmlspecialchars($_POST['treatment']) : ''; ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="notes" class="form-label">医嘱</label>
                                <textarea class="form-control" id="notes" name="notes" rows="3"><?php echo isset($_POST['notes']) ? htmlspecialchars($_POST['notes']) : ''; ?></textarea>
                            </div>
                        </div>
                    </div>

                    <!-- 处方信息 -->
                    <div class="card mb-4">
                        <div class="card-header bg-danger text-white d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">处方信息</h5>
                            <button type="button" class="btn btn-sm btn-light" id="add_medicine">
                                <i class="fas fa-plus"></i> 添加药品
                            </button>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered" id="prescription_table">
                                    <thead>
                                        <tr>
                                            <th style="width: 25%;">药品名称</th>
                                            <th style="width: 15%;">用法用量</th>
                                            <th style="width: 15%;">频次</th>
                                            <th style="width: 10%;">天数</th>
                                            <th style="width: 10%;">数量</th>
                                            <th style="width: 15%;">备注</th>
                                            <th style="width: 10%;">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- 这里将动态添加行 -->
                                        <tr id="no_medicines" <?php echo isset($_POST['medicine_id']) && count($_POST['medicine_id']) > 0 ? 'class="d-none"' : ''; ?>>
                                            <td colspan="7" class="text-center">暂无药品信息，请点击"添加药品"按钮添加</td>
                                        </tr>
                                        
                                        <?php if (isset($_POST['medicine_id'])): ?>
                                            <?php foreach ($_POST['medicine_id'] as $key => $medicine_id): ?>
                                                <tr class="medicine-row">
                                                    <td>
                                                        <select class="form-select medicine-select" name="medicine_id[]" required>
                                                            <option value="">选择药品</option>
                                                            <?php 
                                                            $medicines->data_seek(0);
                                                            while ($med = $medicines->fetch_assoc()): 
                                                            ?>
                                                                <option value="<?php echo $med['id']; ?>" 
                                                                        data-unit="<?php echo htmlspecialchars($med['unit']); ?>"
                                                                        data-price="<?php echo $med['price']; ?>"
                                                                        <?php echo $med['id'] == $medicine_id ? 'selected' : ''; ?>>
                                                                    <?php echo htmlspecialchars($med['name'] . ' (' . $med['specification'] . ')'); ?>
                                                                </option>
                                                            <?php endwhile; ?>
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control" name="dosage[]" placeholder="如：一次1片" value="<?php echo htmlspecialchars($_POST['dosage'][$key]); ?>" required>
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control" name="frequency[]" placeholder="如：一日3次" value="<?php echo htmlspecialchars($_POST['frequency'][$key]); ?>" required>
                                                    </td>
                                                    <td>
                                                        <input type="number" class="form-control days-input" name="days[]" min="1" value="<?php echo htmlspecialchars($_POST['days'][$key]); ?>" required>
                                                    </td>
                                                    <td>
                                                        <div class="input-group">
                                                            <input type="number" class="form-control quantity-input" name="quantity[]" min="1" value="<?php echo htmlspecialchars($_POST['quantity'][$key]); ?>" required>
                                                            <span class="input-group-text medicine-unit"><?php echo isset($_POST['medicine_unit'][$key]) ? htmlspecialchars($_POST['medicine_unit'][$key]) : ''; ?></span>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <input type="text" class="form-control" name="medicine_notes[]" placeholder="备注" value="<?php echo htmlspecialchars($_POST['medicine_notes'][$key]); ?>">
                                                    </td>
                                                    <td>
                                                        <button type="button" class="btn btn-sm btn-danger remove-medicine">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div class="d-grid gap-2 d-md-flex justify-content-md-end mb-4">
                        <a href="records.php" class="btn btn-secondary me-md-2">取消</a>
                        <button type="submit" class="btn btn-primary">保存病历</button>
                    </div>
                </form>
            </main>
        </div>
    </div>

    <!-- 药品行模板 -->
    <template id="medicine_row_template">
        <tr class="medicine-row">
            <td>
                <select class="form-select medicine-select" name="medicine_id[]" required>
                    <option value="">选择药品</option>
                    <?php 
                    $medicines->data_seek(0);
                    while ($med = $medicines->fetch_assoc()): 
                    ?>
                        <option value="<?php echo $med['id']; ?>" 
                                data-unit="<?php echo htmlspecialchars($med['unit']); ?>"
                                data-price="<?php echo $med['price']; ?>">
                            <?php echo htmlspecialchars($med['name'] . ' (' . $med['specification'] . ')'); ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </td>
            <td>
                <input type="text" class="form-control" name="dosage[]" placeholder="如：一次1片" required>
            </td>
            <td>
                <input type="text" class="form-control" name="frequency[]" placeholder="如：一日3次" required>
            </td>
            <td>
                <input type="number" class="form-control days-input" name="days[]" min="1" value="3" required>
            </td>
            <td>
                <div class="input-group">
                    <input type="number" class="form-control quantity-input" name="quantity[]" min="1" value="1" required>
                    <span class="input-group-text medicine-unit"></span>
                </div>
            </td>
            <td>
                <input type="text" class="form-control" name="medicine_notes[]" placeholder="备注">
            </td>
            <td>
                <button type="button" class="btn btn-sm btn-danger remove-medicine">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        </tr>
    </template>

    <!-- 脚本 -->
    <script src="/assets\js/jquery-3.6.0.min.js"></script></script></script>
    <script src="/assets\js/bootstrap.bundle.min.js"></script></script></script>
    <script src="/assets\js/select2_1caa5276.min.js"></script></script></script></script>
    <script>
        $(document).ready(function() {
            // 初始化Select2
            $('.select2').select2({
                theme: 'bootstrap-5'
            });
            
            // 表单验证
            (function () {
                'use strict'
                var forms = document.querySelectorAll('.needs-validation')
                Array.prototype.slice.call(forms)
                    .forEach(function (form) {
                        form.addEventListener('submit', function (event) {
                            if (!form.checkValidity()) {
                                event.preventDefault()
                                event.stopPropagation()
                            }
                            form.classList.add('was-validated')
                        }, false)
                    })
            })();
            
            // 加载患者信息
            $('#patient_id').change(function() {
                var patientId = $(this).val();
                if (patientId) {
                    $.ajax({
                        url: 'ajax/get_patient_info.php',
                        type: 'GET',
                        data: { id: patientId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                var patient = response.data;
                                var today = new Date();
                                var birthDate = new Date(patient.birthday);
                                var age = today.getFullYear() - birthDate.getFullYear();
                                
                                // 检查生日是否已过
                                var m = today.getMonth() - birthDate.getMonth();
                                if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
                                    age--;
                                }
                                
                                var html = `
                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <p><strong>姓名：</strong> ${patient.name}</p>
                                        </div>
                                        <div class="col-md-4">
                                            <p><strong>性别：</strong> ${patient.gender}</p>
                                        </div>
                                        <div class="col-md-4">
                                            <p><strong>年龄：</strong> ${age}岁</p>
                                        </div>
                                    </div>
                                    <div class="row mb-3">
                                        <div class="col-md-4">
                                            <p><strong>身份证：</strong> ${patient.id_card}</p>
                                        </div>
                                        <div class="col-md-4">
                                            <p><strong>电话：</strong> ${patient.phone}</p>
                                        </div>
                                        <div class="col-md-4">
                                            <p><strong>地址：</strong> ${patient.address}</p>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <p><strong>既往病史：</strong> ${patient.medical_history ? patient.medical_history.replace(/\n/g, '<br>') : '无'}</p>
                                        </div>
                                        <div class="col-md-6">
                                            <p><strong>过敏史：</strong> ${patient.allergy ? patient.allergy.replace(/\n/g, '<br>') : '无'}</p>
                                        </div>
                                    </div>
                                `;
                                
                                $('#patient_info').html(html).removeClass('d-none');
                            } else {
                                alert('获取患者信息失败：' + response.message);
                                $('#patient_info').addClass('d-none');
                            }
                        },
                        error: function() {
                            alert('服务器错误，请稍后再试');
                            $('#patient_info').addClass('d-none');
                        }
                    });
                } else {
                    $('#patient_info').addClass('d-none');
                }
            });
            
            // 添加药品行
            $('#add_medicine').click(function() {
                var template = document.getElementById('medicine_row_template');
                var clone = template.content.cloneNode(true);
                
                // 初始化新行中的select2
                setTimeout(function() {
                    $(clone).find('.medicine-select').select2({
                        theme: 'bootstrap-5',
                        dropdownParent: $('#prescription_table')
                    });
                }, 0);
                
                $('#prescription_table tbody').append(clone);
                $('#no_medicines').addClass('d-none');
                
                // 绑定事件
                bindMedicineEvents();
            });
            
            // 删除药品行
            function bindMedicineEvents() {
                $('.remove-medicine').off('click').on('click', function() {
                    $(this).closest('tr').remove();
                    if ($('#prescription_table .medicine-row').length === 0) {
                        $('#no_medicines').removeClass('d-none');
                    }
                });
                
                $('.medicine-select').off('change').on('change', function() {
                    var unit = $(this).find(':selected').data('unit') || '';
                    $(this).closest('tr').find('.medicine-unit').text(unit);
                });
                
                // 计算数量
                $('.days-input, .quantity-input').off('change').on('change', function() {
                    updateQuantity($(this).closest('tr'));
                });
            }
            
            // 更新药品数量
            function updateQuantity(row) {
                var dosage = row.find('[name="dosage[]"]').val();
                var frequency = row.find('[name="frequency[]"]').val();
                var days = parseInt(row.find('[name="days[]"]').val());
                
                if (dosage && frequency && !isNaN(days)) {
                    // 这里简单处理，实际可能需要更复杂的计算
                    var match = frequency.match(/(\d+)次/);
                    var times = match ? parseInt(match[1]) : 1;
                    
                    match = dosage.match(/(\d+)片|(\d+)粒|(\d+)袋|(\d+)支|(\d+)瓶/);
                    var per = match ? parseInt(match[0]) : 1;
                    
                    var quantity = per * times * days;
                    row.find('[name="quantity[]"]').val(quantity);
                }
            }
            
            // 初始绑定事件
            bindMedicineEvents();
        });
    </script>
</body>
</html> 